<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\VideoLibraryCheckRequest;
use App\Http\Requests\Admin\VideoLibraryStoreRequest;
use App\Imports\VideoImport;
use App\Models\LearnVideo;
use App\Models\VideoLibrary;
use App\Models\VideoLibraryCategory;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class VideoLibraryController extends AdminBaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return JsonResponse|object
     */
    public function index()
    {
        $list = VideoLibrary::filter(\request()->all())->orderByRaw('id desc')->paginate(\request('perPage', 10));
        return $this->restful($list);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param VideoLibraryStoreRequest $request
     * @return JsonResponse|object
     */
    public function store(VideoLibraryStoreRequest $request)
    {
        $params = $request->validated();
        $video = VideoLibrary::create($params);

        return $this->restful($video);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return JsonResponse|object
     */
    public function destroy(int $id)
    {
        $res = VideoLibrary::where('id', $id)->delete();
        return $this->restful();
    }

    public function find(VideoLibraryCheckRequest $request)
    {
        $params = $request->validated();
        $video = VideoLibrary::where('name', $params['name'])->where('video_md5', $params['md5'])->first();
        return $this->restful($video);
    }

    public function getOptions()
    {
        $list = VideoLibrary::select(['id as value', 'name as label', 'video_url as url'])->get()->toArray();

        return $this->restful($list);
    }

    public function getCategory()
    {
        $list = VideoLibraryCategory::orderByRaw('sort asc, id asc')->get();

        return $this->restful($list);
    }

    public function storeCategory()
    {
        $params = \request()->validate([
            'name' => 'bail|required|string',
            'sort' => 'bail|nullable|int'
        ], \request()->all());

        $exists = VideoLibraryCategory::where('name', $params['name'])->exists();
        if ($exists) throw new \Exception('分组已存在');

        if (empty($params['sort'])) $lastSort = VideoLibraryCategory::orderByDesc('sort')->value('sort');
        else $lastSort = $params['sort'];

        VideoLibraryCategory::create(['name' => $params['name'], 'sort' => $lastSort ?? 1]);

        return $this->restful();
    }

    public function updateCategory()
    {
        $params = \request()->validate([
            'name' => 'bail|required|string',
            'id' => 'bail|required|int'
        ], \request()->all());

        $category = VideoLibraryCategory::find($params['id']);
        if (!$category) throw new \Exception('分类不存在');

        $exists = VideoLibraryCategory::where('id', '<>', $category->id)->where('name', $params['name'])->exists();
        if ($exists) throw new \Exception('分组已存在');

        $category->name = $params['name'];
        $category->save();

        return $this->restful();
    }

    public function deleteCategory()
    {
        $id = \request('id');
        $category = VideoLibraryCategory::where('id', $id)->delete();

        // 分类下视频归为0
        VideoLibrary::where('category_id', $id)->update(['category_id' => 0]);

        return $this->restful();
    }


    /**
     * excel导入视频
     * @return JsonResponse|object
     */
    public function importVideoByExcel()
    {
        $params = \request()->validate([
            'categoryId' => 'bail|nullable',
            'file' => 'bail|required|file'
        ], \request()->all());

        Excel::import(new VideoImport(!empty($params['categoryId']) ? $params['categoryId'] : 0), $params['file']);
        return $this->restful();
    }

    /**
     * 入库视频
     * @return JsonResponse|object
     */
    public function storeVideos()
    {
        $params = \request()->validate([
            'categoryId' => 'bail|nullable|int',
            'name' => 'bail|nullable|string',
            'format' => 'bail|required|string',
            'size' => 'bail|required|numeric',
            'second' => 'bail|required|numeric',
            'url' => 'bail|required|string',
            'thumb' => 'bail|nullable|string',
            'filePath' => 'bail|nullable|string',
            'fileDriver' => 'bail|nullable|string',
            'videoMd5' => 'bail|nullable|string'
        ], \request()->all());

        $video = VideoLibrary::create([
            'category_id' => !empty($params['categoryId']) ? $params['categoryId'] : 0,
            'name' => $params['name'],
            'total_size' => $params['size'],
            'total_second' => $params['second'],
            'video_url' => $params['url'],
            'video_format' => $params['format'],
            'thumb' => !empty($params['thumb']) ? $params['thumb'] : null,
            'file_path' => !empty($params['filePath']) ? $params['filePath'] : null,
            'file_driver' => !empty($params['fileDriver']) ? $params['fileDriver'] : null,
            'video_md5' => !empty($params['videoMd5']) ? $params['videoMd5'] : null,
        ]);

        // 更新分类数量
        if (!empty($params['categoryId']))
            VideoLibraryCategory::where('id', $params['categoryId'])->increment('videoCount');

        return $this->restful();

    }
}
